package serverMgr

import (
	"fmt"

	"gitee.com/night-tc/gobige/msgdef/protomsg"
)

//防止后续逻辑有修改，先不直接用嵌套了 looby{rand}

// 优先分配小服务ID
type ServerMapByMinID struct {
	ServerMapByRand
}

func NewServerMapByMinID() (result *ServerMapByMinID) {
	result = new(ServerMapByMinID)
	result.Srvli = make(map[uint64]map[uint64]IServerInfo)
	return
}

// 根据负载逻辑，获取服务器
func (this *ServerMapByMinID) GetBalancing(stype, groupid uint32) (result IServerInfo, err error) {
	this.Lock.RLock()
	defer this.Lock.RUnlock()
	result = nil
	key := uint64(stype)<<32 + uint64(groupid)
	if li, ok := this.Srvli[key]; ok {
		//优先使用服务器号更小的
		for _, v := range li {
			if v.GetStatus() != protomsg.ServerStatus_DefaultOK {
				continue
			}
			if result == nil {
				result = v
				continue
			}
			if result.GetServerID() > v.GetServerID() {
				result = v
				continue
			}
		}

		if result != nil {
			if result.GetLoad() < 80 {
				return result, nil
			}

		}

		//如果最小id服务器负载不满足，这里会使用基本分配规则
		for _, v := range li {
			if v.GetLoad() < 80 {
				return v, nil
			}
			if result == nil {
				result = v
				continue
			}
			if v.GetLoad() < 90 {
				if result != nil && result.GetLoad() > v.GetLoad() {
					result = v
				}
			}
		}
	}
	if result == nil {
		return result, fmt.Errorf("Server list is empty, Type %d", stype)
	}
	return
}
